﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml;
using HtmlAgilityPack;
using static System.Net.Mime.MediaTypeNames;

namespace SearchEngineApp
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            InitializeHtmlAgilityPack();
        }

        private void InitializeHtmlAgilityPack()
        {
            // 初始化HtmlAgilityPack设置（可选）
            HtmlNode.ElementsFlags["form"] = HtmlElementFlag.Empty;
        }

        private async void btnSearch_Click(object sender, EventArgs e)
        {
            string keyword = txtKeyword.Text.Trim();
            if string.IsNullOrEmpty(keyword))
            {
                MessageBox.Show("请输入搜索关键字");
                return;
            }

            // 禁用按钮防止重复点击
            btnSearch.Enabled = false;
            txtBaiduResult.Clear();
            txtBingResult.Clear();

            try
            {
                // 并行执行两个搜索引擎的搜索任务
                var baiduTask = SearchBaidu(keyword);
                var bingTask = SearchBing(keyword);
                await Task.WhenAll(baiduTask, bingTask);

                txtBaiduResult.Text = baiduTask.Result;
                txtBingResult.Text = bingTask.Result;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"搜索过程中发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                btnSearch.Enabled = true;
            }
        }

        private async Task<string> SearchBaidu(string keyword)
        {
            string url = $"https://www.baidu.com/s?wd={WebUtility.UrlEncode(keyword)}";
            return await ProcessSearchResult(url, ParseBaiduContent);
        }

        private async Task<string> SearchBing(string keyword)
        {
            string url = $"https://www.bing.com/search?q={WebUtility.UrlEncode(keyword)}";
            return await ProcessSearchResult(url, ParseBingContent);
        }

        private async Task<string> ProcessSearchResult(string url, Func<HtmlDocument, string> parser)
        {
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.UserAgent.ParseAdd("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36");

                var response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode();

                var html = await response.Content.ReadAsStringAsync();
                var doc = new HtmlDocument();
                doc.LoadHtml(html);

                string content = parser(doc);
                return TruncateContent(content, 200);
            }
        }

        private string ParseBaiduContent(HtmlDocument doc)
        {
            var nodes = doc.DocumentNode.SelectNodes("//div[@class='result']");
            return ExtractTextFromNodes(nodes);
        }

        private string ParseBingContent(HtmlDocument doc)
        {
            var nodes = doc.DocumentNode.SelectNodes("//li[@class='b_algo']");
            return ExtractTextFromNodes(nodes);
        }

        private string ExtractTextFromNodes(IEnumerable<HtmlNode> nodes)
        {
            if (nodes == null) return string.Empty;

            var textBuilder = new StringBuilder();
            foreach (var node in nodes)
            {
                // 提取正文内容并去除标签
                string text = node.InnerText.Trim();
                text = Regex.Replace(text, @"\s+", " "); // 替换连续空白字符
                textBuilder.Append(text).AppendLine();
            }
            return textBuilder.ToString();
        }

        private string TruncateContent(string content, int maxLength)
        {
            if (string.IsNullOrEmpty(content)) return string.Empty;
            return content.Length > maxLength ? content.Substring(0, maxLength) : content;
        }

        #region 窗体设计器生成的代码
        private System.Windows.Forms.TextBox txtKeyword;
        private System.Windows.Forms.Button btnSearch;
        private System.Windows.Forms.TextBox txtBaiduResult;
        private System.Windows.Forms.TextBox txtBingResult;
        private System.Windows.Forms.Label label1;
        private System.Windows.Forms.Label label2;
        private System.Windows.Forms.Label label3;

        private void InitializeComponent()
        {
            this.txtKeyword = new System.Windows.Forms.TextBox();
            this.btnSearch = new System.Windows.Forms.Button();
            this.txtBaiduResult = new System.Windows.Forms.TextBox();
            this.txtBingResult = new System.Windows.Forms.TextBox();
            this.label1 = new System.Windows.Forms.Label();
            this.label2 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.SuspendLayout();
            // 
            // txtKeyword
            // 
            this.txtKeyword.Location = new System.Drawing.Point(72, 28);
            this.txtKeyword.Name = "txtKeyword";
            this.txtKeyword.Size = new System.Drawing.Size(456, 25);
            this.txtKeyword.TabIndex = 0;
            // 
            // btnSearch
            // 
            this.btnSearch.Location = new System.Drawing.Point(534, 26);
            this.btnSearch.Name = "btnSearch";
            this.btnSearch.Size = new System.Drawing.Size(75, 28);
            this.btnSearch.TabIndex = 1;
            this.btnSearch.Text = "搜索";
            this.btnSearch.UseVisualStyleBackColor = true;
            this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
            // 
            // txtBaiduResult
            // 
            this.txtBaiduResult.Location = new System.Drawing.Point(22, 100);
            this.txtBaiduResult.Multiline = true;
            this.txtBaiduResult.Name = "txtBaiduResult";
            this.txtBaiduResult.ReadOnly = true;
            this.txtBaiduResult.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtBaiduResult.Size = new System.Drawing.Size(320, 300);
            this.txtBaiduResult.TabIndex = 2;
            // 
            // txtBingResult
            // 
            this.txtBingResult.Location = new System.Drawing.Point(360, 100);
            this.txtBingResult.Multiline = true;
            this.txtBingResult.Name = "txtBingResult";
            this.txtBingResult.ReadOnly = true;
            this.txtBingResult.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
            this.txtBingResult.Size = new System.Drawing.Size(320, 300);
            this.txtBingResult.TabIndex = 3;
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(19, 31);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(49, 15);
            this.label1.TabIndex = 4;
            this.label1.Text = "关键字：";
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(19, 82);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(64, 15);
            this.label2.TabIndex = 5;
            this.label2.Text = "百度结果：";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Location = new System.Drawing.Point(357, 82);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(64, 15);
            this.label3.TabIndex = 6;
            this.label3.Text = "必应结果：";
            // 
            // MainForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(704, 433);
            this.Controls.Add(this.label3);
            this.Controls.Add(this.label2);
            this.Controls.Add(this.label1);
            this.Controls.Add(this.txtBingResult);
            this.Controls.Add(this.txtBaiduResult);
            this.Controls.Add(this.btnSearch);
            this.Controls.Add(this.txtKeyword);
            this.Name = "MainForm";
            this.Text = "多搜索引擎搜索工具";
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion

        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}